package com.linln.admin.pcs.controller;


import com.linln.admin.pcs.service.NotificationMiddleService;
import com.linln.admin.system.service.AppService;
import com.linln.common.data.QuerySpec;
import com.linln.common.utils.HttpServletUtil;
import com.linln.common.utils.ResultVoUtil;
import com.linln.common.utils.ValidationUtil;
import com.linln.component.actionLog.annotation.EntityParam;
import com.linln.component.shiro.ShiroUtil;
import com.linln.modules.system.domain.*;
import com.linln.modules.system.repository.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;


/**
 * 陪诊陪检管理
 */
@Controller
@RequestMapping("/pcs/project/inspection")
public class ProjectInspectionController {

    @Autowired
    private AppService appService;

    @Autowired
    private  ProjectRepository projectRepository;
    @Autowired
    private ContractTplRepository contractTplRepository;
    @Autowired
    private CompanyRepository companyRepository;
    @Autowired
    private UserRepository  userRepository;
    @Autowired
    private NotificationMiddleService notificationMiddleService;


    /**
     * 陪诊陪检项目列表页面
     */
    @GetMapping("/index")
    @RequiresPermissions("pcs:projectInspection:index")
    public ResponseEntity<?> index(Model model, @EntityParam Project project) {
        return appService.layTable(projectRepository, before -> {
                    model.addAttribute("verifyStatus", HttpServletUtil.getParameter("verifyStatus",""));
                    // 添加模板变量
                    return model;

                },

                after -> {

                    QuerySpec querySpec = QuerySpec.matching();
                    querySpec.withMatcher("title", QuerySpec.LIKE)
                            .withMatcher("type", QuerySpec.EQUAL)
                            .withMatcher("verifyStatus", QuerySpec.EQUAL);
                    List<Object> typeList = new ArrayList<>();
                    typeList.add(2);
                    typeList.add(3);
                    querySpec.withMatcherIn("type", typeList);

                    User user = ShiroUtil.getSubject();
                    if (user.getType()!=null&&user.getType().equals("2")) {
                        Long companyId = user.getCompanyId();
                        querySpec.withMatcherValue("companyId", QuerySpec.EQUAL,companyId.toString());
                    }
                    return QuerySpec.of(querySpec);
                },

                "/pcs/project_inspection/index",

                (pageResult) -> {
                    // 在这里处理 pageResult
                    pageResult.getContent().forEach(item -> {
                        Project v = (Project) item;
                        Company company = companyRepository.getById(v.getCompanyId());
                        if(company!=null){
                            v.setCompanyName(company.getName());
                        }
                    });
                }

        );

    }


    /**
     * 表单
     */
    @RequestMapping("/form")
    @RequiresPermissions("pcs:projectInspection:add")
    public ResponseEntity<?> form(Model model, @EntityParam Project project) throws Exception {

        return appService.form(projectRepository, "/pcs/project_inspection/form",
                (isEdit) -> {
                    QuerySpec querySpec = QuerySpec.matching();
                    querySpec.withMatcherValue("companyId", QuerySpec.EQUAL, ShiroUtil.getSubject().getCompanyId().toString())
                            .withMatcherValue("verifyStatus", QuerySpec.EQUAL, "1");;
                    List<ContractTpl> contractTplList = contractTplRepository.findAll(QuerySpec.of(querySpec));
                    model.addAttribute("contractTplList", contractTplList);
                    return model;

                },
                (isEdit, vo) -> {

                    model.addAttribute("vo", vo);
                    // 你可以在这里添加其他逻辑
                    return model;
                },
                (data) -> {
                    // 保存前数据校验
                    List<ValidationUtil.ValidationRule<?>> rules = new ArrayList<>();
//                    Project p = (Project) data;
                    if(project.getIsNeedSignContract()==1){
                        rules.add(new ValidationUtil.ValidationRule<>(
                                "contractTplId",
                                Objects::isNull,
                                "请选择合同模板"
                        ));
                    }


                    // 执行校验
                    return ValidationUtil.validateFields(rules);

                },
                (data) -> {

                    // 数据处理
                    if(project.getId() != null){
                        Project origin = projectRepository.getById(project.getId());
                        project.setStatus(origin.getStatus());
                        project.setCompanyId(origin.getCompanyId());
                        project.setCreateUser(origin.getCreateUser());
                        project.setCreateTime(origin.getCreateTime());
                    }else{
                        User user = ShiroUtil.getSubject();
                        project.setCompanyId(user.getCompanyId());
                        project.setCompanyName(user.getCompanyName());
                    }
                    Company company = companyRepository.findById(project.getCompanyId()).get();
                    project.setIsWl(company.getIsWl());
                    project.setStatus((byte) 1);
                    project.setVerifyStatus(0);
                    return project;
                },

                (data) -> {
                    // 保存后续逻辑在这写
                });

    }



    @PostMapping("/save")
    @RequiresPermissions("pcs:projectInspection:add")
    public ResponseEntity<?> save(Project project, HttpServletRequest request) throws Exception {
        // 解码 content
        if (project.getContent() != null) {
            project.setContent(URLDecoder.decode(project.getContent(), "UTF-8"));
        }
        // 数据处理
        if(project.getId() != null){
            Project origin = projectRepository.getById(project.getId());
            project.setStatus(origin.getStatus());
            project.setCompanyId(origin.getCompanyId());
            project.setCreateUser(origin.getCreateUser());
            project.setCreateTime(origin.getCreateTime());
        }else{
            User user = ShiroUtil.getSubject();
            project.setCompanyId(user.getCompanyId());
            project.setCompanyName(user.getCompanyName());
        }
        if( project.getIsNeedSignContract()==1){
            if(project.getContractTplId()==null || project.getContractTplId()==0 ){
                return ResponseEntity.ok(ResultVoUtil.error("请选择合同模板"));
            }
        }

        project.setStatus((byte) 1);
        project.setVerifyStatus(0);
        Company company = companyRepository.findById(project.getCompanyId()).get();
        project.setIsWl(company.getIsWl());
        projectRepository.save(project);

        //推送数据到中台
        String content = "您有一个陪诊陪检项目【"+project.getTitle()+"】需要审核，请及时处理";
        QuerySpec querySpecUser = QuerySpec.matching();
        querySpecUser.withMatcherValue("type", QuerySpec.EQUAL, "0");
        List<User> userList = userRepository.findAll(QuerySpec.of(querySpecUser));
        userList.forEach(user -> {
            notificationMiddleService.send(content,  "/pcs/inspection/index?verifyStatus=0", user.getMiddleUserId(), request);
        });

        return ResponseEntity.ok(ResultVoUtil.success("成功"));
    }


    @RequestMapping("/detail")
    public String detail(@RequestParam Long id, Model model) throws Exception{
        Project projectOrgin = projectRepository.getById(id);
        model.addAttribute("vo",projectOrgin);
        QuerySpec querySpec1 = QuerySpec.matching();
        querySpec1.withMatcherValue("companyId", QuerySpec.EQUAL, ShiroUtil.getSubject().getCompanyId().toString());
        List<ContractTpl> contractTplList = contractTplRepository.findAll(QuerySpec.of(querySpec1));
        model.addAttribute("contractTplList", contractTplList);
        return "/pcs/project_inspection/detail";
    }
    /**
     * 修改状态
     * @param model
     * @param project
     * @return
     * @throws Exception
     */
    @RequestMapping("/state")
    @RequiresPermissions("pcs:projectInspection:state")
    public ResponseEntity<?> state(Model model, @EntityParam Project project) throws Exception {

        return appService.save(projectRepository, (data) -> {

            // 校验数据
            return ValidationUtil.validateFields(new ArrayList<>());

        }, (data) -> {
            // 处理数据
            Project origin = projectRepository.getById(project.getId());
            origin.setStatus(project.getStatus());

            return origin;

        }, (data) -> {
            // 更新后操作
        });

    }










}
